use Operation;

package AlterPosition;

@ISA = qw/Operation/;

sub perform{
    my $self = shift;
    my ($pos, $map, $direction) = ($self->params->{POS},
				      $self->params->{MAP},
				      $self->params->{DIRECTION});


    my $success = $self->getNewPos($pos, $direction, $map);

    my $lm = $self->{LogManager};
    $lm->log("POS AFTER(".$pos->[0].", ".$pos->[1].")");

    return ActionResult->new("SUCCESS", "OK") if($success);
    return ActionResult->new("FAILURE", "Out of bounds!");
}

# Parameters:
# Reference to an array with [x, y] coordinates
# A direction
# A map
#
# Results: 
# The array's coordinates are updated
# If they would have fallen out of the map, they are left pointing in the nearest valid position (if it would have been -1, it is left as 0)
# Returns 1 if no problems
# Returns 0 if the new position would have fallen out of the map
sub getNewPos{
    my $self = shift;
    my $lm = $self->{LogManager};

    my ($pos, $dir, $map) = (shift, shift, shift);
    my ($w, $h) = ($map->width, $map->height);
    
    $lm->log($dir);
    $dir = uc($dir);
    $lm->log($dir);
    $lm->log("MAP(h".$h.", w".$w.")");
    $lm->log("POS BEFORE(".$pos->[0].", ".$pos->[1].")");
    if($dir eq "UP"){
    $lm->log("UP--");
	return 0 if($pos->[1] == 0);
	$pos->[1] -= 1;
    }
    if($dir eq "DOWN"){
    $lm->log("DOWN--");
	return 0 if($pos->[1] == $h-1);
	$pos->[1] += 1;
    }
    if($dir eq "LEFT"){
    $lm->log("LEFT--");
	return 0 if($pos->[0] == 0);
	$pos->[0] -= 1; 
    }
    if($dir eq "RIGHT"){
    $lm->log("RIGHT--");
	return 0 if($pos->[0] == $w-1);
	$pos->[0] += 1;
    }

    return 1;
}

1;
